package com.cl.websocketboot.controller;

import com.cl.websocketboot.constant.Constant;
import com.cl.websocketboot.entity.Message;
import com.cl.websocketboot.utils.JsonUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.messaging.handler.annotation.DestinationVariable;
import org.springframework.messaging.handler.annotation.MessageMapping;
import org.springframework.messaging.simp.SimpMessagingTemplate;
import org.springframework.messaging.simp.annotation.SubscribeMapping;
import org.springframework.stereotype.Controller;
import org.springframework.util.ObjectUtils;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

@Controller
@Slf4j
public class MessageController {
    private final SimpMessagingTemplate simpMessagingTemplate;

    public MessageController(SimpMessagingTemplate simpMessagingTemplate) {
        this.simpMessagingTemplate = simpMessagingTemplate;
    }

    // @SubscribeMapping 是当前谁调用，返回的数据就给谁
    // 该接口的作用是, 当用户进入房间后, 获取该房间内的所有聊天记录
    @SubscribeMapping("/room/allMessage/{roomId}")
    public Object getAllMessages(@DestinationVariable("roomId") String roomId) {
        List<Message> messageList = Constant.messagesOfRoom.get(roomId);

        if (null == messageList) {
            messageList = new ArrayList<>();
        }

        return messageList;
    }

    // 用户发送信息，给指定房间内的所有的用户发送信息
    @MessageMapping("/room/{roomId}/{username}")
    public void sendMsg(@DestinationVariable("roomId") String roomId,
                        @DestinationVariable("username") String username, String text) {
        Message message = new Message();
        message.setMsgId(UUID.randomUUID().toString());
        message.setContent(text);
        message.setRoomId(roomId);
        message.setUsername(username);
        message.setSendDateTime(LocalDateTime.now());

        Constant.saveMsg(roomId, message);
        // /room/" + roomId + "/message
        final String messageJson = JsonUtil.toString(message);
        if (ObjectUtils.isEmpty(messageJson)) {
            log.error("消息：[{}] 转换失败", text);
            return;
        }
        simpMessagingTemplate.convertAndSend("/room/" + roomId + "/message", messageJson);
    }

}
